<template>
  <!-- 标题 -->
  <div class="animate__animated animate__backInUp">
       <p>
         <CnBoldP class='mt-11 text-20'>坐标管理</CnBoldP>
       </p>
        <p class="mt-10">
          <CnNormalP>根据您设置的坐标，将设备所在的位置以地图的形式呈现</CnNormalP>
        </p>
    <div class="map_box mt-10">
      <a-card  style="border-radius: 10px" :loading="isMapCardLoading">
        <!-- 搜索框组件 -->
        <a-card v-if="isSearch" class="header-card  animate__animated animate__backInLeft " :class="{'animate__backOutLeft':!isSearch}" style="width: 310px">
          <div class="search-box">
            <a-form layout="inline">
               <a-form-item label="设备名称">
                <a-select
                allowClear
                v-model:value="searchFormData.devSearchName"
                show-search
                placeholder="请选择"
                style="width: 200px"
                :options="punctuationDataList"
                :fieldNames="{
                  label: 'title',
                  value: 'title'
                }"
                @change="punctuationSelectChange"
              >
                </a-select>
              </a-form-item>
            </a-form>
          </div>
          <div style="" class="zd_search_icon_box" @click="onShowSearchClick">
            <LeftOutlined />
          </div>
        </a-card>
        <!-- 搜索框小型搜索图标 -->
         <a-tooltip v-else placement="left">
            <template #title>
              <span>显示搜索框</span>
            </template>
            <a-card @click="()=>{isSearch = true}"  class="header-card search_card" style="width: 44px;height:44px;border-radius: 50%;margin-bottom: 10px;"  >
               <SearchOutlined style="margin-left: 4px;margin-top: -8px;"  />
            </a-card>
          </a-tooltip>
        <!-- 未设置设备设备列表小型搜索图标 -->
        <a-tooltip v-if="!isShowIsNotSetListCard" placement="left">
            <template #title>
              <span>显示未设置坐标设备列表</span>
            </template>
           <a-card  @click="()=>{isShowIsNotSetListCard = true}"  class="isNotSetDevListIconCard search_card" style="width: 44px;height:44px;"   >
              <UnorderedListOutlined style="margin-left: 4px;margin-top: -8px;"  />
           </a-card>
        </a-tooltip>


        <!-- 未设置设备坐标列表组件 -->
        <a-card v-else class="isNotSetDevListListCard animate__animated animate__backInLeft" :class="{'animate__backOutLeft':!isShowIsNotSetListCard}">
          <p class="title_box">
            <img src="https://d.lohand.com:1112/images/ConstantBlueCloud/WEB/jg.png" class="w-30" alt="">
            <span>未设置坐标设备列表</span>
          </p>
          <a-list size="small" bordered :data-source="isNotSetDevList" style="width: 300px; height: 380px; overflow-y: scroll;">
             <template #renderItem="{ item }">
               <a-list-item class="isNotSetListItem_box">
               <span> {{ item.title }}</span>
               <a-button type="primary" @click="setCoordinateClick(item)">设置坐标</a-button>
              </a-list-item>
             </template>
          </a-list>
          
           <a-card class="notSetList_icon_card" style="" @click="()=>{isShowIsNotSetListCard = false}">
            <div class="ss_icon_box">
              <LeftOutlined/>
             </div>
           </a-card>


          
        </a-card>

        <!-- 地图组件 -->
        <baidu-map
          class="bm-view"
          :center="{lng:cityCord[0], lat: cityCord[1]}"
          :zoom="13"
          :min-zoom="1"
          :max-zoom="50"
          :scroll-wheel-zoom="true"
          :double-click-zoom="false"
          @dblclick="getLocalPunctuationClick"
        >


          <div v-for="pl in showMapPunctuationDataList" :key="pl.id">
          
            <bm-marker
              :position="{lng: pl.lng, lat: pl.lat}"
              :icon="{
                url: `${pl.status=='在线'?'https://d.lohand.com:1112/images/ConstantBlueCloud/WEB/leida.gif':'https://d.lohand.com:1112/images/ConstantBlueCloud/WEB/sblx.png'}`,
                size: {width: 70, height: 70}
              }"
              :dragging="false"
              @dblclick="(e:any)=>{
                punctuationDbClick(e,pl)
              }"
              @mouseover="punctuationMouseover(pl)"
              @mouseout="punctuationMouseout(pl)"
            >
              <my-overlay
               :position="{lng: pl.lng, lat: pl.lat}"
               :text="textOmitFunc(pl.title)">
              </my-overlay>
               <markToolTip
               :data="pl"
               :position="{lng: pl.lng, lat: pl.lat}"
               :text="textOmitFunc(pl.title)"
               style="transition: 2s; height: 0px;"
              
               >
              </markToolTip>
            </bm-marker>
          </div> 

                   <!-- <bm-traffic :predictDate="{weekday: 7, hour: 12}">
    </bm-traffic> -->
       <!-- <bm-boundary name="杭州市上城区" :strokeWeight="2" strokeColor="blue"></bm-boundary> -->
           <bm-overview-map anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :isOpen="true"></bm-overview-map>
               <bm-city-list anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-city-list>
          </baidu-map>


           <devNumberCard class="devNumberCard" :devSumNumber="devSumNumber" :devOnLineNumber="devOnLineNumber" :devOffLineNumber="devOffLineNumber"></devNumberCard>
    </a-card>


    <!-- 修改设备坐标的弹窗组件 -->
      <a-modal
        v-model:visible="isShowEditPunctuationModal"
        title="修改设备坐标"
        @ok="editPunctuationModalOkClick"
        @cancel="editPunctuationModalCancelClick"
      >
        <div class="editPunctuationModal_box">
          <p>
            <div class="title_box">
              <CnMediumP style="margin-right: 10px;"> 当前设备 </CnMediumP>
               <CnBoldP>{{ currentEditDevPunctuationTitle }}</CnBoldP>
            </div>
          </p>
          <p style="">
            <span style="margin-right: 10px">经度</span>
            <a-input style="width: 160px" v-model:value="editCoordinateForm.lng" />
            <span style="margin: 0px 10px 0px 50px">纬度</span>
            <a-input style="width: 160px" v-model:value="editCoordinateForm.lat" />
          </p>
          <p style="margin: 10px 0px ;">
            <span>或</span>
          </p>
          <p>
            <a-button type="primary" @click="getLocalPunctuationBtnClick">选择获取坐标</a-button>
          </p>
        </div>
      </a-modal>


       <!-- 设置设备坐标的弹窗组件 -->
      <a-modal
        v-model:visible="isShowSetDevPunctuation"
        title="设置设备坐标"
        @ok="editPunctuationModalOkClick"
        @cancel="editPunctuationModalCancelClick"
      >
        <div class="editPunctuationModal_box">
          <p>
            <div class="title_box">
              <CnMediumP style="margin-right: 10px;"> 当前设备 </CnMediumP>
               <CnBoldP>{{ currentSetDevPunctuationInfo.title }}</CnBoldP>
            </div>
          </p>
          <p style="">
            <span style="margin-right: 10px">经度</span>
            <a-input style="width: 160px" v-model:value="currentSetDevPunctuationInfo.lng" />
            <span style="margin: 0px 10px 0px 50px">纬度</span>
            <a-input style="width: 160px" v-model:value="currentSetDevPunctuationInfo.lat" />
          </p>
          <p style="margin: 10px 0px ;">
            <span>或</span>
          </p>
          <p>
            <a-button type="primary" @click="chooseGetCoordinateClick">选择获取坐标</a-button>
          </p>
        </div>
      </a-modal>
    </div>
     
  </div>
  <!-- 选择设备坐标的提示信息组件 -->
  <div>
      <a-alert v-if="isMapPunctuationEdit" message="请双击地图中某个位置来获取坐标" type="info" class="mapPunctuationEditMsgAlert" />
  </div>



   <!-- 未设置设备坐标的提示信息组件 -->
  <div>
      <a-alert v-if="isShowNotSetDevMsg" message="请点击地图左侧的未设置坐标的设备列表进行设置设备坐标" type="info" class="mapPunctuationEditMsgAlert" />
  </div>
</template>

<script lang="ts">
import {defineComponent, onMounted} from 'vue'
export default defineComponent({
  name: 'coordinateManagement'
})
</script>
<!-- <script type="text/javascript" src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=kvzowTSFQXlM4GtypkSWMtTDnGqoU18g"></script> -->
<script lang="ts" setup>
import Header from './header/index.vue'
import {SearchOutlined, LeftOutlined,UnorderedListOutlined} from '@ant-design/icons-vue'
import {selectDevCoordinateApi,editDevCoordinateApi} from '@/api/coordinateManagement'
// import MyOverlay from '../../components/MyOverlay.vue'
import {CnMediumP, CnBoldP} from '@/components/text'
import MyOverlay from './mapMark/index.vue'
import markToolTip from './mapMark/markToolTip.vue'
import devNumberCard from './numberCard/index.vue'
import {message} from 'ant-design-vue'
import { getUserId } from '@/libs/auth'
import { getCityCord } from '@/utils/cityCoordinates/index.ts'


// 地图卡片的加载状态的标识
const isMapCardLoading = ref(false)


// 当前城市坐标信息
const cityCord = ref([])

// 设备的总数量
const devSumNumber = ref(0)

// 设备的在线数量 
const devOnLineNumber = ref(0)

// 设备的离线数量
const devOffLineNumber = ref(0)





// 鼠标移入标点的事件
const punctuationMouseover = (pl:any) => {
  console.log('移入');
  console.log(pl);
  showMapPunctuationDataList.value.forEach((item: any) => {
    if (item.id == pl.id) {
      item.isShowMarkToopTip = true
    }
  })
}


const punctuationMouseout = (pl:any) => {
  console.log('移出');
  console.log(pl);
   showMapPunctuationDataList.value.forEach((item: any) => {
    if (item.id == pl.id) {
      item.isShowMarkToopTip = false
    }
  })
}


// 鼠标移出标点的事件



// 是设置还是修改的标识
const isSet = ref(false)

/* 设备设置坐标 start ----------------------------------- */

// 是否显示设置设备坐标的弹窗
const isShowSetDevPunctuation = ref(false)

// 当前设置设备坐标的信息
const currentSetDevPunctuationInfo = ref({
  id: '',
  gid:'',
  lng: '',
  lat: '',
  title: '',
  status:''
})


// 设置坐标的点击事件
const setCoordinateClick = (item: any) => {
  isSet.value = true
  isShowSetDevPunctuation.value = true
  console.log(item);
  currentSetDevPunctuationInfo.value = item
}

// 选择获取坐标的点击事件
const chooseGetCoordinateClick = () => {
   isMapPunctuationEdit.value = true
   isShowSetDevPunctuation.value = false
}



/* 设备设置坐标 end ----------------------------------- */

// 当前修改设备坐标的Id
const currentDevId = ref('')

// 是否显示未设置设备坐标列表卡片的标识
const isShowIsNotSetListCard = ref(false)

// 处理标点文字过长出现省略号的函数
const textOmitFunc = (str: string) => {
  let newStr = ''
  if (str.length > 7) {
    for (let i = 0; i < str.length; i++) {
      if (i < 7) {
        newStr += str[i]
      }
    }
    newStr += '...'
  } else {
    newStr = str
  }
  return newStr
}

// 显示搜索的点击事件
const showSearchClick = () => {
  isSearch.value = true
}
const onShowSearchClick = () => {
  isSearch.value = false
}

// 搜索状态显示的标识
const isSearch = ref(false)
// 当前是否是修改状态的标识
const isMapPunctuationEdit = ref(false)

// 点击选择获取坐标按钮的点击事件
const getLocalPunctuationBtnClick = (e: any) => {
  isMapPunctuationEdit.value = true
  isShowEditPunctuationModal.value = false
  console.log(e)
}

// 地图的双击事件获取坐标信息
const getLocalPunctuationClick = (e: any) => {
  if (isSet.value) {
    currentSetDevPunctuationInfo.value.lng = e.point.lng
    currentSetDevPunctuationInfo.value.lat = e.point.lat
   
    showMapPunctuationDataList.value.forEach(item => {
    if (item.title == currentSetDevPunctuationInfo.value.title) {
      item.lng = e.point.lng
      item.lat = e.point.lat
    }
    })
     isShowSetDevPunctuation.value = true
     isMapPunctuationEdit.value = false
     message.success(
    `获取\t ${currentEditDevPunctuationTitle.value} \t坐标成功,经度(${e.point.lng}),纬度(${e.point.lat})`
  )
  } else {
     if (!isMapPunctuationEdit.value) return
  editCoordinateForm.value.lng = e.point.lng
  editCoordinateForm.value.lat = e.point.lat
  showMapPunctuationDataList.value.forEach(item => {
    if (item.title == currentEditDevPunctuationTitle.value) {
      item.lng = e.point.lng
      item.lat = e.point.lat
    }
  })
  isShowEditPunctuationModal.value = true
  isMapPunctuationEdit.value = false
  console.log(e)
  message.success(
    `获取\t ${currentEditDevPunctuationTitle.value} \t坐标成功,经度(${e.point.lng}),纬度(${e.point.lat})`
  )
  }
 
}

// 当前修改设备坐标的标题
const currentEditDevPunctuationTitle = ref('')

// 修改标点坐标的经度和维度收集的数据
const editCoordinateForm = ref({
  lng: 0,
  lat: 0
})

// 当前标签原本的坐标信息的数据
const currentOldCoordinate = ref({
  lng: 0,
  lat: 0
})

// 修改标点坐标弹窗的确定点击事件
const editPunctuationModalOkClick =async () => {
  console.log(editCoordinateForm.value)
 
 
  console.log('确定')

  if (isSet.value) {
    isShowSetDevPunctuation.value = false
    await editDevCoordinateApi({
      devId: currentSetDevPunctuationInfo.value.id,
      longitude: currentSetDevPunctuationInfo.value.lng,
      latitude: currentSetDevPunctuationInfo.value.lat
    }).then(() => {
      message.success('设置设备坐标成功!')
    }).catch(() => {
      message.error('设置设备坐标失败,请联系管理员')
    })
  } else {
    isShowEditPunctuationModal.value = false,
      await editDevCoordinateApi({
      devId: currentDevId.value,
      longitude: editCoordinateForm.value.lng,
      latitude: editCoordinateForm.value.lat
    }).then(() => {
      message.success('修改设备坐标成功!')
    }).catch(() => {
      message.error('修改设备坐标失败,请联系管理员')
    })
  }

  selectDevCoordinateFunc()
  // platFormSubUserId.value = getUserId()
}

// 修改标点坐标弹窗的取消点击事件
const editPunctuationModalCancelClick = () => {
  console.log(editCoordinateForm.value)
  let editOldPunctuation = {
    lng: 0,
    lat: 0
  }

  punctuationDataList.value.forEach(item => {
    if (item.title == currentEditDevPunctuationTitle.value) {
      item.lng = currentOldCoordinate.value.lng
      item.lat = currentOldCoordinate.value.lat
    }
  })

  showMapPunctuationDataList.value.forEach(item => {
    if (item.title == currentEditDevPunctuationTitle.value) {
      item.lng = currentOldCoordinate.value.lng
      item.lat = currentOldCoordinate.value.lat
    }
  })
  isShowEditPunctuationModal.value = false
  console.log('取消')
}

// 修改标点坐标的弹窗显示的标识
const isShowEditPunctuationModal = ref(false)

// 地图标点的双击事件
const punctuationDbClick = (e: any, info: any) => {
  isSet.value = false
  currentDevId.value = info.id
  if (isMapPunctuationEdit.value) return
  isShowEditPunctuationModal.value = true
  currentEditDevPunctuationTitle.value = info.title
  console.log(e, info)
  showMapPunctuationDataList.value.forEach((item: any) => {
    if (item.id == info.id) {
      editCoordinateForm.value.lng = info.lng
      editCoordinateForm.value.lat = info.lat
      currentOldCoordinate.value.lng = info.lng
      currentOldCoordinate.value.lat = info.lat
    }
  })

  console.log( currentDevId.value );
  
}

// 搜索选择框的change事件
const punctuationSelectChange = (e: any) => {
  showMapPunctuationDataList.value = []
  console.log(e)
  let newArr = []
  if (e != undefined) {
    punctuationDataList.value.forEach((item: any) => {
      if (item.title == e) {
        showMapPunctuationDataList.value.push(item)
      }
    })
  } else {
    showMapPunctuationDataList.value = punctuationDataList.value
  }
}

// 搜索的表单数据
const searchFormData = ref({
  devSearchName: ''
})

// 标点的坐标数据
const punctuationDataList = ref([
  // {
  //   id: 1,
  //   lng: 119.99321,
  //   lat: 30.304634,
  //   title: '杭州西站'
  // },
  // {
  //   id: 2,
  //   lng: '',
  //   lat: '',
  //   title: '杭州站'
  // },
  // {
  //   id: 3,
  //   lng: 120.219396,
  //   lat: 30.297149,
  //   title: '杭州东站'
  // },
  // {
  //   id: 4,
  //   lng: 120.300366,
  //   lat: 30.177844,
  //   title: '杭州南站'
  // },
  // {
  //   id: 5,
  //   lng: 120.585888,
  //   lat: 30.020511,
  //   title: '绍兴站'
  // },
  // {
  //   id: 6,
  //   lng: 120.545177,
  //   lat: 30.105338,
  //   title: '绍兴北站'
  // },
  // {
  //   id: 7,
  //   lng: '',
  //   lat: '',
  //   title: '陆恒'
  // }
])

interface PunctuationDataType {
  id: number
  lng: number
  lat: number
  title: string
}
// 地图上显示的标点数据
const showMapPunctuationDataList = ref<PunctuationDataType[]>([])

// 获取坐标数据的函数
const selectDevCoordinateFunc = async () => {
  isMapCardLoading.value = true
  const userId = getUserId()
  const res = await selectDevCoordinateApi({platFormSubUserId: userId})
  console.log(res)
  disposeResDataFunc(res.data.devCoordinateRspList,res.data.devCount)
  // console.log(disposeData,'disposeData');
  // console.log(res.data.mainArea);
  cityCord.value = getCityCord(res.data.mainArea)
 isMapCardLoading.value= false
}

// 处理请求响应数据的函数
const disposeResDataFunc = (data: [], devCount: number) => {
  let sumNum = devCount
  let onLineNum = 0
  let offLineNum = 0


  let newArr = [] || null
  let newNoSetArr = []||null
  console.log(data);
  data.forEach((item: any) => {
    if (item.longitude != "" && item.longitude!=null && item.longitude !=undefined   && item.latitude != "" && item.latitude != null && item.latitude != undefined) {
    newArr.push({
      id: item.devId,
      gid: item.devGId,
      title: item.devName,
      lng: item.longitude,
      lat: item.latitude,
      status: item.devStatus,
      isShowMarkToopTip:false
    })
    } else {
      newNoSetArr.push({
      id: item.devId,
      gid: item.devGId,
      title: item.devName,
      lng: item.longitude,
      lat: item.latitude,
      status:item.devStatus
      })
    }


    // 计算设备在线数量和离线数量
    if (item.devStatus == '在线') {
      onLineNum += 1
    } else {
      offLineNum += 1
    }
  })
  showMapPunctuationDataList.value = newArr
  punctuationDataList.value = newArr
  isNotSetDevList.value = newNoSetArr
  devSumNumber.value = sumNum
  devOnLineNumber.value = onLineNum
  devOffLineNumber.value = offLineNum
}

// 未设置坐标的设备列表
const isNotSetDevList = ref([])


// 是否显示未设置设备坐标提示组件的标识
const isShowNotSetDevMsg = ref(true)
onMounted(() => {
  // console.log(textOmitFunc('123456789'))
  setTimeout(() => {
    isShowNotSetDevMsg.value = false
  },3000)
  selectDevCoordinateFunc()
  // showMapPunctuationDataList.value = punctuationDataList.value
})
</script>
<style lang="less" scoped>
.map_box {
  border-radius: 30px;
  position: relative;
  ::v-deep .ant-card-body {
    padding: 10px;
  }
  .bm-view {
    padding: 0px;
    border-radius: 20px;
    width: 100%;
    height: 77vh;
  }
  .header-card {
    border-radius: 10px;
    z-index: 100;
    position: absolute;
    top: 20px;
    left: 1%;
    // background: rgba(255, 255, 255, 0.9);
    // transform: translate(-50%, 0);
  }

  .isNotSetDevListIconCard{
  border-radius: 10px;
  z-index: 100;
  position: absolute;
  top: 80px;
  left: 1.2%;
}

.isNotSetDevListListCard{
  border-radius: 10px;
  position: absolute;
  z-index: 100;
  top: 80px;
  left: 1.2%;
  

  .title_box{
    display: flex;
    flex-direction: row;
    line-height: 30px;
    // justify-content: space-around;
    padding: 6px 0px 6px 46px;
// background: url(https://d.lohand.com:1112/images/ConstantBlueCloud/WEB/nowifi.png);  
    img{
      margin-right: 10px;
      
    }
    span{
      font-weight: bold;
      font-size: 18px;
    }
  }
}
}
.editPunctuationModal_box {
  padding: 30px 30px;

  .title_box {
    width: 300px;
    display: flex;
    margin-bottom: 20px;
  }
}

.mapPunctuationEditMsgAlert {
  position: fixed;
  top: 100px;
  left: 50%;
  transform: translate(0, -50%);
}
// .header-card {
//   width: 100%;
//   margin-bottom: 20px;

//   .search-box {
//     display: flex;
//     flex-direction: row;

//     .dev-search-name-input {
//       width: 300px;
//     }
//   }
//   // svg {
//   //   vertical-align: initial !important;
//   // }
// }
// .BMapLabel {

// }
.animate__backInUp {
  --animate-duration: 0.4s;
}

.search_icon_box {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  font-size: 20px;
  line-height: 20px;
  padding-left: 3px;
  cursor: pointer;
}

.search_icon_box:hover {
  color: #1d7bef;
  font-weight: bold;
}

.zd_search_icon_box {
  width: 50px;
  height: 50px;
  background: white;
  border-radius: 50%;
  position: absolute;
  top: 1px;
  right: -23px;
  font-size: 16px;
  line-height: 45px;
  padding-left: 15px;
  font-weight: 200;
  color: #7e7c7c;
  cursor: pointer;
}
.zd_search_icon_box:hover {
  color: #1d7bef;
}


.search_card{
  cursor: pointer;
}

.notSetList_icon_card{
    width: 40px;
    margin-top: 10px;
    position: absolute;
    right: -50px;
    top: 50%;
    transform: translate(0% ,-50%);
    border-radius: 10px;
    cursor: pointer;
}


::v-deep .ant-list-item:hover{
  transition: 0.3s;
  background: #f1f4f9;
}

// ::v-deep .isNotSetListItem_box{
//   dis
// }

.h_200{
  height: 200px !important;
}
.h_0{
  height: 0px !important;
}



/* 隐藏地图左下角的百度地图的logo和文字信息 */
::v-deep .anchorBL{
  display: none !important;
}


.devNumberCard{
  position: absolute;
  bottom: 16px;
  left: 16px;
}
</style>